# -*-coding:utf8-*-


#from biliwatcher import readConfig # 导包这样导
from nonebot import require
from nonebot import get_bot
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from bilimonitor import bili
from bilimonitor import sql
from bilimonitor import config


scheduler = require("nonebot_plugin_apscheduler").scheduler

all_live_status = {}


# 每分钟查询一次动态，发送新动态给用户
@scheduler.scheduled_job('interval',minutes=1)
async def _():
    database = sql.Database(config.DATABASE_ADDRESS, config.DATABASE_ACCOUNT, config.DATABASE_PASSWORD, config.DATABASE_NAME, config.DATABASE_PORT)

    # 先发送动态
    all_dynamic_list = bili.getAllDynamic(database)
    for qq, dynamic in all_dynamic_list:
        # 先发送文字
        try:
            await get_bot().call_api(
                    'send_private_msg', 
                    user_id = qq,
                    message = dynamic.content['text']
                    )
        except:
            print('机器人发送动态失败')
        
        # 再发送图片（如果有）
        if dynamic.content['pic']:
            pic = ''
            # 带图动态，将图片链接转为CQ码，再发送
            for link in dynamic.content['pic']:
                pic = pic + '[CQ:image,file=' + link + ']'
            
            try:
                await get_bot().call_api(
                    'send_private_msg', 
                    user_id = qq,
                    message = pic
                    )
            except:
                print('机器人发送图片时出错')

    # 再发送直播状态
    live_follow = database.getLiveFollowList()
    for uid in live_follow:
        live_status = bili.getLiveStatus(uid)# 返回二元组(直播状态，直播标题)
        if uid not in all_live_status:
            all_live_status[uid] = live_status[0]
        else:
            if (not all_live_status[uid]) and (live_status[0]):
                # 向用户发送开播信息
                for user in live_follow[uid]:
                    try:
                        await get_bot().call_api(
                            'send_private_msg', 
                            user_id = user,
                            message = database.getUserName(uid) + '开播了：' + live_status[1]
                        )
                    except:
                        print('发送直播状态失败')
            # 更改直播状态
            all_live_status[uid] = live_status[0]



insertFollow = on_command('添加关注', rule = to_me(), priority = 5)
@insertFollow.handle()
async def handle(bot : Bot, event : Event, state : T_State):
    uid = str(event.get_message()).strip() # 添加的用户uid
    try:
        # 获取关注列表
        database = sql.Database(config.DATABASE_ADDRESS, config.DATABASE_ACCOUNT, config.DATABASE_PASSWORD, config.DATABASE_NAME, config.DATABASE_PORT)
        qq = event.get_session_id()
        status = database.insertDynamicFollow(uid, qq)
        if status:
            name = database.getUserName(uid)
            if name:
                msg = f'已添加用户 {name}(uid:{uid}) 到关注列表中'
                await get_bot().call_api('send_private_msg', user_id = qq, message = msg)
            else:
                await get_bot().call_api('send_private_msg', user_id = qq, message = '获取用户信息失败，请检查uid')
        else:
            await get_bot().call_api('send_private_msg', user_id = qq, message = '添加关注失败')

        # 发送信息
    except:
        insertFollow.reject('添加关注失败')